package com.guc.aidltest

import aidl.IAIDLService
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import com.guc.aidltest.databinding.ActivityMainBinding
import com.guc.gviewbinding.inflate

class MainActivity : AppCompatActivity() {
    private val mainBinding: ActivityMainBinding by inflate()
    private var aidlService: IAIDLService? = null

    private val connection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            aidlService = IAIDLService.Stub.asInterface(service)
            try {
                mainBinding.tvShow.text = aidlService?.getString()
            } catch (e: RemoteException) {
                e.printStackTrace()
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            aidlService = null
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainBinding.btnBindService.setOnClickListener {
            val intent = Intent("com.guc.aidlservice.AIDLService").apply {
                `package` = "com.guc.aidlservice"
            }
            bindService(intent, connection, BIND_AUTO_CREATE)
        }
        mainBinding.btnUnBindService.setOnClickListener {
            unbindService(connection)
        }

    }
}